package org.darcy.youchat.activity.home;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import org.darcy.youchat.R;
import org.darcy.youchat.activity.BaseActivity;
import org.darcy.youchat.activity.message.UserInfoActivity;
import org.darcy.youchat.databinding.ActivitySearchUserBinding;
import org.darcy.youchat.nimsdk.NimUserInfoSDK;
import org.darcy.youchat.utils.KeyBoardUtils;
import org.darcy.youchat.utils.UIUtils;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.List;

/**
 * 搜索用户（本地、网上）
 */
public class SearchUserActivity extends BaseActivity {

    private ActivitySearchUserBinding binding;

    private NimUserInfo mUser;

    /**
     * 搜索框，在toolbar中
     */
    EditText mEtSearch;

    public static final String SEARCH_TYPE = "search_type";
    public boolean isSearchUserLocal = SEARCH_USER_LOCAL;
    public static final boolean SEARCH_USER_LOCAL = false;
    public static final boolean SEARCH_USER_REMOTE = true;


    @Override
    public void init() {
        //isSearchUserLocal = getIntent().getBooleanExtra(SEARCH_TYPE, SEARCH_USER_LOCAL);
    }

    @Override
    public void initView() {
        binding = ActivitySearchUserBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.mToolbar.toolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        binding.mToolbar.toolbar.setNavigationIcon(R.mipmap.ic_back);
        mEtSearch = binding.mToolbar.etSearch;
        mEtSearch.setVisibility(View.VISIBLE);
        mEtSearch.setHintTextColor(UIUtils.getColor(R.color.gray2));
        mEtSearch.setTextColor(UIUtils.getColor(R.color.white));
    }

    @Override
    public void initListener() {
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                binding.rlNoResultTip.setVisibility(View.GONE);
                if (TextUtils.isEmpty(mEtSearch.getText().toString().trim())) {
                    binding.llSearch.setVisibility(View.GONE);
                } else {
                    binding.llSearch.setVisibility(View.VISIBLE);
                    binding.tvMsg.setText(s);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //监听键盘回车或搜索
        mEtSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                if (TextUtils.isEmpty(mEtSearch.getText().toString().trim())) {
                    KeyBoardUtils.closeKeyboard(mEtSearch, SearchUserActivity.this);
                } else {
                    doSearch();
                }
                return true;
            }
            return false;
        });

        binding.llSearch.setOnClickListener(v -> doSearch());
    }

    private void doSearch() {
        showWaitingDialog("请稍等");
        String account = mEtSearch.getText().toString().trim();
        if (isSearchUserLocal) {
            mUser = NimUserInfoSDK.getUser(account);
            searchDone();
        } else {
            NimUserInfoSDK.getUserInfoFromServer(account, new RequestCallback<List<NimUserInfo>>() {
                @Override
                public void onSuccess(List<NimUserInfo> param) {
                    if (param.size() > 0) {
                        mUser = param.get(0);
                    }
                    searchDone();
                }

                @Override
                public void onFailed(int code) {
                    UIUtils.showToast("搜索失败" + code);
                    hideWaitingDialog();
                }

                @Override
                public void onException(Throwable exception) {
                    exception.printStackTrace();
                    hideWaitingDialog();
                }
            });
        }
    }

    private void searchDone() {
        hideWaitingDialog();
        if (mUser == null) {
            binding.rlNoResultTip.setVisibility(View.VISIBLE);
        } else {
            binding.rlNoResultTip.setVisibility(View.GONE);
            //跳转到用户信息界面
            Intent intent = new Intent(this, UserInfoActivity.class);
            intent.putExtra("account", mUser.getAccount());
            startActivity(intent);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }


}
